/**
 * Created by Administrator on 2017/7/24.
 */
var integralList = new Object();
var page;
var company_name;
var companyIds = [];
var deptIds = [];
var comPIds = [];
var userObject = [];
var userCompanyId = $("#userCompanyId").val(); // 当前登陆用户所在的companyId
/**
 * checkbox 点击事件
 * @param selectedNode
 */
var userIdAll = [];
var object = {};
// 初始化
integralList.init = function (page1) {
    page = page1;
    $("#recursion").attr("checked",false);
    window.groupTree_search = integralList.search;
    window.groupTree_rightClick = integralList.onRightClick;
    groupTree.init({"ifShow":"false"});
    integralList.addDefaultNode();

    this.initTable();
};

integralList.initTable = function () {
    var companyId = $("#companyId").val();
    $("#deptIds").val(companyId);
    var rootNode = getRoots()[0];
    integralList.getAllchildrenNodes(comPIds, rootNode, rootNode.type);

    var selectedNodes = $.fn.zTree.getZTreeObj("group_tree").getSelectedNodes();
    var selectedNode = selectedNodes[0];
    integralList.treeSearch(selectedNode);

};

integralList.initListTable = function (url) {
    var list_url = url;
    var selectedNodes = $.fn.zTree.getZTreeObj("group_tree").getSelectedNodes();
    var selectedNode = selectedNodes[0];
    var cid = selectedNode.companyId;

    /*
     * 分页
     * @param param_form 参数form id
     * @param list_url 请求链接
     * @param tbody_id 列表div id
     * @param page_id 分页id
     * @param pageNum 页数
     * @param pageSize 每页条数
     */
    page.init("userListForm", list_url, "user_tbody", "user_page", 1, 10);

    //初始化
    page.goPage(1);

    //重写组装方法
    page.list = function (dataList) {
        var len = dataList.length;
        var inner = "", item;
        var nodeType = $("#nodeType").val();
        for (var i = 0; i < len; i++) {
            item = dataList[i];
            // 组装数据
            inner += "<tr>";
            inner += "<td width='40'>" + (parseInt(i) + 1) + "</td>";
            inner += "<td width='50' ><input type='checkbox' id='userId_" + i + "' title='" + item.userType + "' name='checkUser' value='" + item.userId + "' companyId='" + item.companyId + "' userName='" + item.userName + "' /></td>";
            inner += "<td width='100'><span class=\"text-orange\">" + item.userName + "</span></td>";
            inner += "<td width='100'>" + item.userAccount + "</td>";
            var company_name = item.companyName;
            if (company_name == '' || company_name == undefined || company_name == null) {
                inner += "<td width='120'>/</td>";
            } else {
                inner += "<td width='120'>" + company_name + "</td>";
            }
            var dept_name = item.deptName;
            if(dept_name){
                dept_name = dept_name.trim();
            }
            if (dept_name == '' || dept_name == undefined || dept_name == null) {
                inner += "<td  width=\"120\">/</td>";
            } else {
                inner += "<td  width=\"120\"><span class=\"text-orange\">" + dept_name + "</span></td>";
            }
            inner += "<td width='72'>" + item.yearIntegral + "</td>";
            inner += "<td width='72'>" + item.allIntegral + "</td>";
            inner += "<td width='100'><a href=\"javascript:void(0);\" class=\"a a-view\" onclick=\"+integralList.historyIntegral('"+item.userId+"')\">历史积分</a>";
            inner += "</td>";
            inner += "</tr>";
        }
        return inner;
    };

};


//历史积分明细
integralList.historyIntegral = function checkHistoricalIntegralDetail(userId) {
    layer.open({
        type: 2,
        title: '历史积分明细',
        area: ['1250px', '800px'],		//弹出层大小
        scrollbar: false,				//false隐藏滑动块
        content: [appPath + '/admin/studentIntegral/historicalIntegralDetail?userId='+userId, 'yes']
    });
}

/**
 * 是否显示子单位节点
 * @param treeNode
 */
integralList.checkboxChange = function () {
    if ($("#recursion").prop("checked")) {
        groupTree.init({"ifShow":"true"});
    }else{
        groupTree.init({"ifShow":"false"});
    }
    integralList.addDefaultNode();
    integralList.search();
};

integralList.search = function (treeNode) {
    // 清空所有已选
    //$("#clearSelAll").trigger("click");
    var selectedNodes = $.fn.zTree.getZTreeObj("group_tree").getSelectedNodes();
    var selectedNode = selectedNodes[0];
    if("1" == selectedNode.type && $("#recursion").prop("checked") == true){
        $("#ifAllSearch").val("true");
    }else{
        $("#ifAllSearch").val("false");
    }
    integralList.treeSearch(selectedNode);
};

//模糊查询
integralList.treeSearch = function (treeNode) {
    $("#user_tbody :checkbox").prop("checked", false);
    // 获取左侧选中节点
    var companyId = (treeNode.companyId) ? treeNode.companyId : "";
    var departmentId = (treeNode.departmentId) ? treeNode.departmentId : "";
    var departmentName = (treeNode.name) ? treeNode.name : "";
    var type = treeNode.type;
    var id = treeNode.id.toString();
    /*$("#departmentId").attr("value", departmentId);
    $("#departmentName").attr("value", departmentName);*/
    $("#nodeType").val(type);
    var url = "admin/studentIntegral/queryList";
    var array = [];
    integralList.getAllchildrenNodes(array,treeNode, type);
    $("#companyId").val(companyId);
    var roleName = $("#roleName").val();
    //type 1:根节点(单位); 2:父节点(单位); 3:叶子节点(部门)
    if ("1" == type || "2" == type) {
        $("#companyIds").val(companyId);
        $("#departmentId").val("");
    }
    if ("3" == type) {
        $("#companyId").val(companyId);
        $("#departmentId").val(departmentId);
    }
    integralList.initListTable(url);
    userIdAll = [];
    object = {};
};


/**
 * 递归查询人员所在单位
 * @param deptId
 * @returns {string}
 */
function getAllParentNodes(deptId) {
    var contactName = '';
    var treeObj = $.fn.zTree.getZTreeObj(tree_options.id);
    var treeNode = treeObj.getNodeByParam("id", deptId, null);
    if (treeNode == null) {
        return "";
    } else if (treeNode.type == "1") {
        return "";
    } else {
        contactName = contactName == '' ? treeNode.name : treeNode.name + '/' + contactName;
        var vl = getAllParentNodes(treeNode.getParentNode().id);
        if (vl != '') {
            contactName = contactName == '' ? vl : vl + '/' + contactName;
        }
    }
    return contactName;
}

//获取某一节点下的所有子节点
integralList.getAllchildrenNodes = function (array, treeNode, type) {
    if("-1" != treeNode.id) {
        array.push(treeNode.id);
    }
    if (treeNode.isParent) {
        var childrenNodes = treeNode.children;
        if (childrenNodes) {
            var len = childrenNodes.length;
            if (type == '3') {
                for (var i = 0; i < len; i++) {
                    integralList.getAllchildrenNodes(array, childrenNodes[i], type);
                }
            } else {
                for (var j = 0; j < len; j++) {
                    if (childrenNodes[j].type == '3') {
                        continue;
                    }
                    integralList.getAllchildrenNodes(array,childrenNodes[j], type);
                }
            }
        }
    }
    return array;
};

//查询全部
integralList.searchAll = function () {
    $("#userName").val("");
    $("#userAccount").val("");
    integralList.search();
};


//搜索高亮
function getFontCss(treeId, treeNode) {
    return (!!treeNode.highlight) ? {'color': "#A60000", 'font-weight': "bold"} : {
        'color': "#333",
        'font-weight': "normal"
    };
}

// 获取根节点集合
function getRoots() {
    var treeObj = $.fn.zTree.getZTreeObj(tree_options.id);
    return treeObj.getNodesByFilter(function (node) {
        return node.level == 0;
    });
}


integralList.getRole = function () {
    var treeObj = $.fn.zTree.getZTreeObj(tree_options.id);
    var rootNode = this.getRoots()[0];
    treeObj.selectNode(rootNode);
    treeObj.setting.callback.onClick(null, tree_options.id, rootNode);
};




/**
 * 全选事件
 */
$("#checkAll").click(function () {
        if (this.checked) {
            $("#user_tbody :checkbox").prop("checked", true);

            $("#user_tbody :checkbox").each(function () {
                if (!object[$(this).val()]) {
                    var item = new Object();
                    item.userId = $(this).val();
                    item.companyId = $(this).attr("companyid");
                    item.userType = $(this).attr("title");
                    item.userName = $(this).attr("username");
                    object[$(this).val()] = 1;
                    userIdAll.push(item);
                }else{
                    if(userIdAll.indexOf($(this).val()) == -1){
                        var item = new Object();
                        item.userId = $(this).val();
                        item.companyId = $(this).attr("companyid");
                        item.userType = $(this).attr("title");
                        item.userName = $(this).attr("username");
                        userIdAll.push(item);
                    }
                }
            });

        } else {
            $("#user_tbody :checkbox").prop("checked", false);
            if (userIdAll.length > 0) {
                for (var a = 0; a < userIdAll.length; a++) {
                    $("#user_tbody :checkbox").each(function () {
                        if ($(this).val() === userIdAll[a].userId) {
                            delete object[$(this).val()];
                            userIdAll.splice(a, 1);
                        }
                    })
                }
            }
        }
    }

);

/**
 * 单选事件
 */
$("#user_tbody").on("click", "input[type=checkbox]", function () {
    if ($(this).is(":checked")) {
        if (!object[$(this).val()]) {
            object[$(this).val()] = 1;
            var item = new Object();
            item.userId = $(this).val();
            item.companyId = $(this).attr("companyid");
            item.userType = $(this).attr("title");
            item.userName = $(this).attr("username");
            userIdAll.push(item);
        }
    } else {
        if (userIdAll.length > 0) {
            for (var a = 0; a < userIdAll.length; a++) {
                if ($(this).val() === userIdAll[a].userId) {
                    delete object[$(this).val()];
                    userIdAll.splice(a, 1);
                }
            }
        }
    }
});
/**
 *
 * 清空所有的选择
 */
$("#clearSelAll").on("click",function(){
    userIdAll = [];
    object={};
});


/**
 * 导出
 */
integralList.exportUser = function () {
    // 获取部门id
    var selectedNodes = $.fn.zTree.getZTreeObj(tree_options.id).getSelectedNodes();
    var treeNode = selectedNodes[0];
    var companyId = (treeNode.companyId) ? treeNode.companyId : "";
    var depId = (treeNode.departmentId) ? treeNode.departmentId : "";
    var departmentName = (treeNode.name) ? treeNode.name : "";
    var type = treeNode.type;
    var array = new Array;

    if(userIdAll.length>0){
        for(var j = 0; j < userIdAll.length; j++){
            array.push(userIdAll[j].userId);
        }
    }
    var arr = array.join(",");
    var fileName = departmentName + "-人员导出.xlsx";

    var flag = $("#recursion").prop("checked");

    companyIds = [];
    if (null != arr && '' != arr) {
        if(arr.length>500){
            layer.msg("您的选择大于500条！");
            return;
        }
        window.location.href = appPath + '/admin/studentIntegral/excel_export?fileName=' + fileName + '&params=' + arr + "&exportTye=1" + "&flag=" + flag;
    } else if ("3" == type) {  //导出部门人员
        if (flag && '-1' == depId) {
            companyIds.push(comPIds);
        } else {
            companyIds.push(companyId);
        }
        //询问框
        layer.confirm('您想要导出' + '<span style="color: blue;font-weight: bold">' + departmentName + '</span>' + '部门下的人员？', {
            btn: ['确定', '取消'], //按钮
            icon: 3
        }, function (index) {
            window.location.href = appPath + '/admin/studentIntegral/excel_export?fileName=' + fileName + '&depId=' + depId + '&companyIds=' + companyIds + "&exportTye=1" + "&flag=" + flag;
            layer.close(index);
        }, function () {
            //取消
        });
    } else {
        var pageTotal = Number($("#pageTotal").val());
        if(pageTotal && !isNaN(pageTotal)){
            if(pageTotal>500){
                layer.msg("数据量大于500,请选择小于500条！");
                return;
            }
        }else{
            return;
        }
        if (flag) {
            companyIds = integralList.getAllchildrenNodes(companyIds, treeNode, type);
        } else {
            companyIds.push(companyId);
        }


        //询问框
        layer.confirm('您想要导出全公司人员？', {
            btn: ['确定', '取消'], //按钮
            icon: 3
        }, function (index) {
            window.location.href = appPath + '/admin/studentIntegral/excel_export?fileName=' + fileName + "&exportTye=1" + "&companyIds=" + companyIds + "&flag=" + flag + "&type=" + type;
            layer.close(index);
        }, function () {
            //取消
        });
    }
};


function modifyUser(userId) {
    var url = appPath + "/admin/user/userModify?id=" + userId ;
    window.open(url);
}


function returnUrl() {
    integralList.search();
}



integralList.addDefaultNode = function () {
    var rootNode = getRoots()[0];
    var treeNode1 = new Object();
    treeNode1.id = '-1';
    treeNode1.pid = rootNode.id;
    treeNode1.name = '离职人员';
    treeNode1.companyId = rootNode.id;
    treeNode1.departmentId = "-1";
    treeNode1.type = '3';
    treeNode1.icon = appPath + "/static/global/js/zTree/css/zTreeStyle/img/department.png";
    groupTree.zTree.addNodes(rootNode, treeNode1, false);
};

//修改
function modifyPassWord(userId) {
    location.href = appPath + '/admin/user/userModify?id=' + userId;
}


integralList.selectUserListByUserType = function (value) {
    console.log(value)
}

